package net.asfun.jvalog.frame;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.asfun.jvalog.common.GMCacher;
import net.asfun.jvalog.entity.File;
import net.asfun.jvalog.resource.FileDao;

public class MediaServlet extends HttpServlet {

	private static final long serialVersionUID = 4321273288183043787L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException{
		String uri = req.getRequestURI();
		File value = (File) GMCacher.get(uri);
		if ( value == null ) {
			int index = uri.lastIndexOf('/');
			String name = uri.substring(index + 1);
			value = FileDao.getByName(name);
			GMCacher.put(uri, value);
		}
		if ( value != null ) {
			resp.setContentType(value.getMime());
			byte[] bts = value.getBytes().getBytes();
			resp.setContentLength(bts.length);
			resp.getOutputStream().write(bts);
			resp.setHeader("Cache-Control", "max-age=1728000, public");
			resp.setHeader("Pragma", "cache");
			long now = new Date().getTime();
			long next = now + 1728000000;//20 day
			resp.setDateHeader("Last-Modified", now);
			resp.setDateHeader("Expires", next);
			resp.setHeader("ETag", Long.toString(now, 32));
			return;
		} else {
			resp.sendError(404);
		}
		
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException{
		resp.sendError(403);
	}
}
